package models

import "database/sql"

// Record is a struct containing Task data
type Record struct {
	ID         int64  `json:"id"`
	Name       string `json:"name"`
	Content    string `json:"content"`
	CreateTime string `json:"createTime"`
}

// RecordkCollection is collection of Tasks
type RecordCollection struct {
	Records []Record `json:"items"`
}

func GetRecords(db *sql.DB) RecordCollection {
	sql := "SELECT id,name,content,createTime FROM records"
	rows, err := db.Query(sql)
	// Exit if the SQL doesn't work for some reason
	if err != nil {
		panic(err)
	}
	// make sure to cleanup when the program exits
	defer rows.Close()

	result := RecordCollection{}
	for rows.Next() {
		record := Record{}
		err2 := rows.Scan(&record.ID, &record.Name, &record.Content, &record.CreateTime)
		// Exit if we get an error
		if err2 != nil {
			panic(err2)
		}
		result.Records = append(result.Records, record)
	}
	return result
}

func PutRecord(db *sql.DB, name string, content string) (int64, error) {
	sql := "INSERT INTO records(name,content) VALUES(?,?)"

	stmt, err := db.Prepare(sql)

	if err != nil {
		panic(err)
	}

	defer stmt.Close()

	result, err2 := stmt.Exec(name, content)

	if err2 != nil {
		panic(err2)
	}

	return result.LastInsertId()
}

func DeleteRecord(db *sql.DB, id int64) (int64, error) {
	sql := "DELETE FROM records WHERE id = ?"

	stmt, err := db.Prepare(sql)

	if err != nil {
		panic(err)
	}

	result, err2 := stmt.Exec(id)

	if err2 != nil {
		panic(err2)
	}

	return result.RowsAffected()
}
